import { defineStore } from 'pinia'
import { shallowRef } from 'vue'
import { Menu } from '@/api/system/menus/type'
import { RouteRecordRaw } from 'vue-router'
import { fetchMenusTreeApi } from '@/api/system/menus'
import router from '@/router/index'
import { getLoginUserApi } from '@/api/system/users'

const useUserStore = defineStore('user', () => {
    const authorities = shallowRef<string[]>([])
    const userInfo = ref()
    const menus = ref()

    async function fetchUserInfo() {
            const res = await getLoginUserApi()
            if (res.data.code == '200') {
                userInfo.value = res.data.data
                const menures = await fetchMenusTreeApi({ name: '' })
                if (menures.data.code == '200') {
                    menus.value = menures.data.data
                    menuToRouter(menures.data.data)
                }
            }
    }

    const modules = import.meta.glob('../views/**/*.vue')
    function menuToRouter(menuTree: Menu[]) {
        let temp: RouteRecordRaw[] = []
        menuTree.forEach(menu => {
            let r: RouteRecordRaw = {
                path: menu.routePath,
                name: menu.routeName,
                component: menu.componentPath ? modules[`../views${menu.componentPath}.vue`] : null,
                children: menuToRouter(menu.children),
                meta: {
                    title: menu.name
                }
            }
            router.addRoute('Root', r)
            temp.push(r)
            authorities.value.push(menu.authority)
        })
        return temp
    }

    return {
        userInfo,
        authorities,
        fetchUserInfo,
        menus
    }
})

export default useUserStore